//
//  PhotoTableViewController.m
//  Paparazzi
//
//  Created by Eric Williams on 10/24/10.
//  Copyright 2010 Eric Williams. All rights reserved.
//

#import "PhotoTableViewController.h"
#import "PhotoDetailViewController.h"
#import "FlickrFetcher.h"
#import "Person.h"
#import "Photo.h"
#import "ImagePreviewDownloader.h"

@implementation PhotoTableViewController

@synthesize person;
@synthesize imagePreviewDownloadsInProgress;
@synthesize imagePreviews;
//@synthesize frController;

- (BOOL)multiUser {
	return multiUser;
}

- (void)setMultiUser: (BOOL) input {
	multiUser = input;
}


/* NOTE: THIS FUNCTIONALITY IS TAKEN CARE OF BY CORE DATA INTERNALLY
#pragma mark -
#pragma mark ContactUpdateDelegate

- (void) contactDeleted {
	// Reset the preview images since a contact has been erased from CoreData
	imagePreviews = nil;
	imagePreviewDownloadsInProgress = nil;
	self.imagePreviewDownloadsInProgress = [NSMutableDictionary dictionary];
	self.imagePreviews = [NSMutableDictionary dictionary];
}
*/

#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad {
    [super viewDidLoad];
	
	flickrFetcher = [FlickrFetcher sharedInstance];
	self.imagePreviewDownloadsInProgress = [NSMutableDictionary dictionary];
	self.imagePreviews = [NSMutableDictionary dictionary];
	
	// Get all the photos
	if(self.multiUser == YES) {
		frController = [[flickrFetcher fetchedResultsControllerForEntity: @"Photo" withPredicate: nil] retain];
		
		// Clear the cache of the previous person/person's results
		[NSFetchedResultsController deleteCacheWithName: frController.cacheName];
		NSError *error = nil;
		[frController performFetch: &error];
	}
	// Get a single users photos
	else {
		// Shorter the back button's name
		UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:[person name] style:UIBarButtonItemStyleBordered target:nil action:nil];
		self.navigationItem.backBarButtonItem = backButton;
		[backButton release];
		
		NSPredicate *personPred = [NSPredicate predicateWithFormat: @"user=%@", person];
		frController = [[flickrFetcher fetchedResultsControllerForEntity: @"Photo" withPredicate: personPred] retain];
		
		// Clear the cache of the previous person/person's results
		[NSFetchedResultsController deleteCacheWithName: frController.cacheName];
		NSError *error = nil;
		[frController performFetch: &error];
	}
	
	// Create the header image view to be passed in later by the delegate
	UIImage *photosImage = [UIImage imageNamed: @"Photos.png"];
	photosHeaderImageView = [[UIImageView alloc] initWithImage: photosImage];	
	
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
	// Clear the cache of the previous people's results and refill it
	[NSFetchedResultsController deleteCacheWithName: frController.cacheName];
	NSError *error = nil;
	[frController performFetch: &error];
	
	// Reset the preview images since a contact has been erased from CoreData
	if(self.multiUser) {
		self.imagePreviews = nil;
		self.imagePreviewDownloadsInProgress = nil;
		self.imagePreviewDownloadsInProgress = [NSMutableDictionary dictionary];
		self.imagePreviews = [NSMutableDictionary dictionary];
	}
	
	// Reload the data
	[self.tableView reloadData];
}

/*
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/


#pragma mark -
#pragma mark Table view data source


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
	NSInteger sectionCount = [[frController sections] count];
	
	// If sections is not a non-0 value, make it at least one
	if (sectionCount == 0) {
		sectionCount = 1;
	}
	
    return sectionCount;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
	
	NSArray *sections = [frController sections];
	NSInteger rowCount = 0;
	
	// If there's a section, count its rows
	if([sections count]) {
		id <NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex: section];
		rowCount = [sectionInfo numberOfObjects];
	}
	
	return rowCount;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
	
	
	// Vary the cell style depending on the load status
	static NSString *CellIdentifier = @"LazyTableCell";
    static NSString *PlaceholderCellIdentifier = @"PlaceholderCell";
    
    // add a placeholder cell while waiting on table data
    int nodeCount = [self.tableView numberOfRowsInSection: 0];
	
	if (nodeCount == 0 && indexPath.row == 0)
	{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:PlaceholderCellIdentifier];
        if (cell == nil)
		{
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
										   reuseIdentifier:PlaceholderCellIdentifier] autorelease];   
            cell.detailTextLabel.textAlignment = UITextAlignmentCenter;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
		
		cell.detailTextLabel.text = @"Loading…";
		
		return cell;
    }
	
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
	{
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
									   reuseIdentifier:CellIdentifier] autorelease];
    }
	
	// Configure the cell for recently viewed photos
	Photo *photo = [frController objectAtIndexPath: indexPath];
	
	// SERVERS - ASYNCHRONOUS
    // Leave cells empty if there's no data yet
    if (nodeCount > 0)
	{
		cell.textLabel.text = [photo name];
		cell.detailTextLabel.text = [NSString stringWithFormat: @"by %@", [[photo user] name]];
		
        // Only load cached images; defer new downloads until scrolling ends
        NSData *previewData = [imagePreviews objectForKey: indexPath];
		if (! previewData)
        {
            if (self.tableView.dragging == NO && self.tableView.decelerating == NO)
            {
                [self startIconDownload: photo forIndexPath: indexPath];
            }
            // if a download is deferred or in progress, return a placeholder image
            cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];                
        }
        else
        {
			cell.imageView.image = [UIImage imageWithData: previewData];
			cell.imageView.frame = CGRectMake(0, 0, 60, 60);
        }
    }
    return cell;
}

-(void) tableView: (UITableView*) tableView willDisplayCell:(UITableViewCell*) cell forRowAtIndexPath:(NSIndexPath*) indexPath {
	if (indexPath.row % 2 == 0) {
		cell.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
	}	
}

#pragma mark -
#pragma mark Table cell image support

- (void)startIconDownload:(Photo *) photo forIndexPath:(NSIndexPath *)indexPath
{
    ImagePreviewDownloader *imagePreviewDownloader = [self.imagePreviewDownloadsInProgress objectForKey:indexPath];
    if (imagePreviewDownloader == nil) 
    {
        imagePreviewDownloader = [[ImagePreviewDownloader alloc] init];
        
		imagePreviewDownloader.myPhoto = photo;
        imagePreviewDownloader.myIndex = indexPath;
        imagePreviewDownloader.delegate = self;
		
        [self.imagePreviewDownloadsInProgress setObject: imagePreviewDownloader forKey:indexPath];
        [imagePreviewDownloader startDownload: @"s"];
        [imagePreviewDownloader release];   
    }
}

// this method is used in case the user scrolled into a set of cells that don't have their app icons yet
- (void)loadImagesForOnscreenRows
{
	// If there are any items in this table...
    if ([self.tableView numberOfRowsInSection: 0])
    {
        NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths)
        {
            Photo *photo = [frController objectAtIndexPath:indexPath];
			[self startIconDownload:photo forIndexPath:indexPath];
        }
    }
}

// called by our ImageDownloader when an icon is ready to be displayed
- (void) previewDownloadedWithData:(NSData *)data forIndex:(NSIndexPath *)index;
{
    ImagePreviewDownloader *imagePreviewDownloader = [self.imagePreviewDownloadsInProgress objectForKey:index];
    if (imagePreviewDownloader != nil)
    {
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath: index];
        
        // Display the newly loaded image
		[self.imagePreviews setObject: data forKey:index];
        cell.imageView.image = [UIImage imageWithData: data];
    }
}


#pragma mark -
#pragma mark Deferred image loading (UIScrollViewDelegate)

// Load images for all onscreen rows when scrolling is finished
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (!decelerate)
	{
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self loadImagesForOnscreenRows];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	// Create a new Detail View	
	PhotoDetailViewController *photoDetailViewController = [[PhotoDetailViewController alloc] init];
	Photo *photo = [frController objectAtIndexPath: indexPath];
	photoDetailViewController.photo = photo;
	
	[self.navigationController pushViewController: photoDetailViewController animated: YES];
	[photoDetailViewController release];
}

// Used to place an image in the main header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
	if(section == 0) {
		return photosHeaderImageView;
	}
	else {
		return nil;
	}
}

// Used to size the main header 
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
	if(section == 0) {
		return 60.0;
	}
	else {
		return 0;
	}
}

// Used to beef up the height on the other cells
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 60;
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
    // For example: self.myOutlet = nil;
}

- (void)dealloc {
	[frController release];
	[imagePreviewDownloadsInProgress release];
	[imagePreviews release];
    [super dealloc];
}


@synthesize flickrFetcher;
@synthesize frController;
@synthesize photosHeaderImageView;
@end

